/**
 * 笔记模型
 * Note Model
 */

const BaseModel = require('./BaseModel');
const logger = require('../../utils/logger');

class Note extends BaseModel {
  constructor() {
    super('notes');
  }

  /**
   * 创建笔记
   */
  async createNote(userId, noteData) {
    try {
      const noteToCreate = {
        user_id: userId,
        title: noteData.title || '无标题笔记',
        content: noteData.content || '',
        tags: noteData.tags ? JSON.stringify(noteData.tags) : null
      };

      const note = await this.create(noteToCreate);
      
      logger.info('笔记创建成功 / Note created successfully', {
        noteId: note.id,
        userId,
        title: note.title
      });

      return note;
    } catch (error) {
      logger.error('创建笔记失败 / Failed to create note', {
        userId,
        title: noteData.title,
        error: error.message
      });
      throw error;
    }
  }

  /**
   * 获取用户的笔记列表
   */
  async getUserNotes(userId, options = {}) {
    try {
      const {
        page = 1,
        pageSize = 20,
        orderBy = 'updated_at DESC',
        includeDeleted = false,
        onlyFavorites = false
      } = options;

      const conditions = { user_id: userId };
      
      if (!includeDeleted) {
        conditions.is_deleted = 0;
      }
      
      if (onlyFavorites) {
        conditions.is_favorite = 1;
      }

      return await this.paginate(conditions, {
        page,
        pageSize,
        orderBy,
        fields: 'id, title, tags, created_at, updated_at'
      });
    } catch (error) {
      logger.error('获取用户笔记列表失败 / Failed to get user notes', {
        userId,
        error: error.message
      });
      throw error;
    }
  }

  /**
   * 获取笔记详情
   */
  async getNoteDetail(noteId, userId) {
    try {
      const note = await this.findOne({
        id: noteId,
        user_id: userId,
        is_deleted: 0
      });

      if (!note) {
        throw new Error('笔记不存在 / Note not found');
      }

      // 增加查看次数
      await this.incrementViewCount(noteId);

      // 解析标签
      if (note.tags) {
        try {
          note.tags = JSON.parse(note.tags);
        } catch (e) {
          note.tags = [];
        }
      } else {
        note.tags = [];
      }

      return note;
    } catch (error) {
      logger.error('获取笔记详情失败 / Failed to get note detail', {
        noteId,
        userId,
        error: error.message
      });
      throw error;
    }
  }

  /**
   * 更新笔记
   */
  async updateNote(noteId, userId, updateData) {
    try {
      // 验证笔记所有权
      const existingNote = await this.findOne({
        id: noteId,
        user_id: userId,
        is_deleted: 0
      });

      if (!existingNote) {
        throw new Error('笔记不存在或无权限 / Note not found or no permission');
      }

      const dataToUpdate = {
        updated_at: new Date()
      };

      // 只更新提供的字段
      if (updateData.title !== undefined) {
        dataToUpdate.title = updateData.title;
      }
      
      if (updateData.content !== undefined) {
        dataToUpdate.content = updateData.content;
      }
      
      if (updateData.tags !== undefined) {
        dataToUpdate.tags = Array.isArray(updateData.tags) 
          ? JSON.stringify(updateData.tags) 
          : updateData.tags;
      }

      const updatedNote = await this.update(noteId, dataToUpdate);

      logger.info('笔记更新成功 / Note updated successfully', {
        noteId,
        userId,
        title: updatedNote.title
      });

      return updatedNote;
    } catch (error) {
      logger.error('更新笔记失败 / Failed to update note', {
        noteId,
        userId,
        error: error.message
      });
      throw error;
    }
  }

  /**
   * 软删除笔记
   */
  async deleteNote(noteId, userId) {
    try {
      // 验证笔记所有权
      const existingNote = await this.findOne({
        id: noteId,
        user_id: userId,
        is_deleted: 0
      });

      if (!existingNote) {
        throw new Error('笔记不存在或无权限 / Note not found or no permission');
      }

      await this.update(noteId, {
        is_deleted: 1,
        deleted_at: new Date()
      });

      logger.info('笔记删除成功 / Note deleted successfully', {
        noteId,
        userId,
        title: existingNote.title
      });

      return true;
    } catch (error) {
      logger.error('删除笔记失败 / Failed to delete note', {
        noteId,
        userId,
        error: error.message
      });
      throw error;
    }
  }

  /**
   * 恢复已删除的笔记
   */
  async restoreNote(noteId, userId) {
    try {
      const existingNote = await this.findOne({
        id: noteId,
        user_id: userId,
        is_deleted: 1
      });

      if (!existingNote) {
        throw new Error('已删除的笔记不存在 / Deleted note not found');
      }

      await this.update(noteId, {
        is_deleted: 0,
        deleted_at: null,
        updated_at: new Date()
      });

      logger.info('笔记恢复成功 / Note restored successfully', {
        noteId,
        userId
      });

      return true;
    } catch (error) {
      logger.error('恢复笔记失败 / Failed to restore note', {
        noteId,
        userId,
        error: error.message
      });
      throw error;
    }
  }

  /**
   * 永久删除笔记
   */
  async permanentDeleteNote(noteId, userId) {
    try {
      // 验证笔记所有权
      const existingNote = await this.findOne({
        id: noteId,
        user_id: userId
      });

      if (!existingNote) {
        throw new Error('笔记不存在或无权限 / Note not found or no permission');
      }

      await this.delete(noteId);

      logger.info('笔记永久删除成功 / Note permanently deleted', {
        noteId,
        userId
      });

      return true;
    } catch (error) {
      logger.error('永久删除笔记失败 / Failed to permanently delete note', {
        noteId,
        userId,
        error: error.message
      });
      throw error;
    }
  }

  /**
   * 搜索笔记
   */
  async searchNotes(userId, keyword, options = {}) {
    try {
      const { page = 1, pageSize = 20 } = options;
      const offset = (page - 1) * pageSize;

      const sql = `
        SELECT id, title, tags, created_at, updated_at
        FROM notes 
        WHERE user_id = ? 
          AND is_deleted = 0 
          AND (title LIKE ? OR content LIKE ?)
        ORDER BY updated_at DESC
        LIMIT ? OFFSET ?
      `;

      const searchTerm = `%${keyword}%`;
      const { rows } = await this.raw(sql, [userId, searchTerm, searchTerm, pageSize, offset]);

      // 获取总数
      const countSql = `
        SELECT COUNT(*) as total 
        FROM notes 
        WHERE user_id = ? 
          AND is_deleted = 0 
          AND (title LIKE ? OR content LIKE ?)
      `;
      const { rows: countRows } = await this.raw(countSql, [userId, searchTerm, searchTerm]);
      const total = countRows[0].total;

      // 处理标签
      const processedRows = rows.map(note => {
        if (note.tags) {
          try {
            note.tags = JSON.parse(note.tags);
          } catch (e) {
            note.tags = [];
          }
        } else {
          note.tags = [];
        }
        return note;
      });

      return {
        data: processedRows,
        pagination: {
          page,
          pageSize,
          total,
          totalPages: Math.ceil(total / pageSize)
        }
      };
    } catch (error) {
      logger.error('搜索笔记失败 / Failed to search notes', {
        userId,
        keyword,
        error: error.message
      });
      throw error;
    }
  }

  /**
   * 获取用户的标签列表
   */
  async getUserTags(userId) {
    try {
      const sql = `
        SELECT tags 
        FROM notes 
        WHERE user_id = ? AND is_deleted = 0 AND tags IS NOT NULL AND tags != ''
      `;

      const { rows } = await this.raw(sql, [userId]);
      
      const tagSet = new Set();
      
      rows.forEach(row => {
        try {
          const tags = JSON.parse(row.tags);
          if (Array.isArray(tags)) {
            tags.forEach(tag => tagSet.add(tag));
          }
        } catch (e) {
          // 忽略解析错误
        }
      });

      return Array.from(tagSet).sort();
    } catch (error) {
      logger.error('获取用户标签失败 / Failed to get user tags', {
        userId,
        error: error.message
      });
      throw error;
    }
  }

  /**
   * 根据标签获取笔记
   */
  async getNotesByTag(userId, tag, options = {}) {
    try {
      const { page = 1, pageSize = 20 } = options;
      const offset = (page - 1) * pageSize;

      const sql = `
        SELECT id, title, tags, created_at, updated_at
        FROM notes 
        WHERE user_id = ? 
          AND is_deleted = 0 
          AND JSON_CONTAINS(tags, ?)
        ORDER BY updated_at DESC
        LIMIT ? OFFSET ?
      `;

      const { rows } = await this.raw(sql, [userId, JSON.stringify(tag), pageSize, offset]);

      // 获取总数
      const countSql = `
        SELECT COUNT(*) as total 
        FROM notes 
        WHERE user_id = ? 
          AND is_deleted = 0 
          AND JSON_CONTAINS(tags, ?)
      `;
      const { rows: countRows } = await this.raw(countSql, [userId, JSON.stringify(tag)]);
      const total = countRows[0].total;

      return {
        data: rows,
        pagination: {
          page,
          pageSize,
          total,
          totalPages: Math.ceil(total / pageSize)
        }
      };
    } catch (error) {
      logger.error('根据标签获取笔记失败 / Failed to get notes by tag', {
        userId,
        tag,
        error: error.message
      });
      throw error;
    }
  }

  /**
   * 增加笔记查看次数 - 简化版本
   */
  async incrementViewCount(noteId) {
    try {
      // 简化版本，不实际更新查看次数
      logger.info('笔记查看次数记录', { noteId });
    } catch (error) {
      logger.error('增加笔记查看次数失败 / Failed to increment view count', {
        noteId,
        error: error.message
      });
      // 不抛出错误，因为这不是关键操作
    }
  }

  /**
   * 获取用户笔记统计
   */
  async getUserNoteStats(userId) {
    try {
      const sql = `
        SELECT 
          COUNT(*) as total_notes,
          COUNT(CASE WHEN is_deleted = 1 THEN 1 END) as deleted_notes
        FROM notes 
        WHERE user_id = ?
      `;

      const { rows } = await this.raw(sql, [userId]);
      const stats = rows[0];
      
      // 添加默认值
      stats.favorite_notes = 0;
      stats.total_views = 0;
      stats.total_words = 0;
      stats.avg_words_per_note = 0;
      
      return stats;
    } catch (error) {
      logger.error('获取用户笔记统计失败 / Failed to get user note stats', {
        userId,
        error: error.message
      });
      throw error;
    }
  }

  /**
   * 获取最近更新的笔记
   */
  async getRecentNotes(userId, limit = 10) {
    try {
      return await this.findMany(
        { user_id: userId, is_deleted: 0 },
        {
          fields: 'id, title, updated_at',
          orderBy: 'updated_at DESC',
          limit
        }
      );
    } catch (error) {
      logger.error('获取最近更新笔记失败 / Failed to get recent notes', {
        userId,
        error: error.message
      });
      throw error;
    }
  }
}

module.exports = new Note();